<?php

namespace App\Models\OpenShop\InvestmentPromotion;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class OpenShopProcessDetailNoticeEmployeeModel extends BaseModel
{
    use HasFactory;

    protected $table = 'open_shop_process_detail_notice_employees';

    protected $fillable = ['orderNo', 'step', 'processType', 'noticeEmployeeUids'];

    public function getNoticeEmployeeUidsAttribute()
    {
        $uids = $this->attributes['noticeEmployeeUids'] ?? '';
        if (!strlen($uids)) {
            return [];
        }
        return explode(',', $uids);
    }

    public function setNoticeEmployeeUidsAttribute(array $val)
    {
        // 自动去重
        $this->attributes['noticeEmployeeUids'] = implode(',', array_unique($val));
    }

    protected static function boot()
    {
        parent::boot();
        static::saving(function (OpenShopProcessDetailNoticeEmployeeModel $m) {
            $m->attributes['noticeEmployeeUids'] = (string)($m->attributes['noticeEmployeeUids'] ?? '');
        });
    }

    /**
     * 删除某人的通知记录
     * @param string $orderNo
     * @param int $oriUid
     * @return void
     */
    public static function replaceUid(string $orderNo, int $oriUid, int $newUid): void
    {
        self::query()->where('orderNo', $orderNo)->get()->each(function ($item) use ($oriUid, $newUid) {

            $noticeEmployeeUids = $item->noticeEmployeeUids;
            $noticeEmployeeUids[] = $newUid;

            foreach ($noticeEmployeeUids as $k => $vUid) {
                if ($oriUid == $vUid) {
                    unset($noticeEmployeeUids[$k]);
                }
            }

            $item->noticeEmployeeUids = $noticeEmployeeUids;
            $item->save();
        });
    }
}
